<template>
  <div class="fullscreen-container" :class="{ 'is-fullscreen': isFullscreen }">
    <!-- 全屏控制按钮 -->
    <div class="fullscreen-controls" v-if="!isFullscreen">
      <n-button
        type="primary"
        @click="enterFullscreen"
        :loading="isLoading"
        class="fullscreen-btn"
      >
        <template #icon>
          <n-icon>
            <Maximize />
          </n-icon>
        </template>
        进入全屏
      </n-button>
    </div>

    <!-- 全屏内容区域 -->
    <div class="fullscreen-content" ref="fullscreenElement">
      <!-- 全屏状态下的顶部控制栏 -->
      <div class="fullscreen-header" v-if="isFullscreen">
        <div class="fullscreen-title">
          <slot name="title">
            <h2>{{ title || 'EduMaster 全屏模式' }}</h2>
          </slot>
        </div>
        
        <div class="fullscreen-actions">
          <n-button
            quaternary
            circle
            @click="exitFullscreen"
            class="exit-btn"
          >
            <template #icon>
              <n-icon size="20">
                <X />
              </n-icon>
            </template>
          </n-button>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="fullscreen-main" :class="{ 'with-header': isFullscreen }">
        <slot>
          <div class="default-content">
            <div class="content-center">
              <n-icon size="64" color="#3b82f6">
                <Maximize />
              </n-icon>
              <h3>全屏显示模式</h3>
              <p>这是一个全屏显示组件示例</p>
              <p>按 ESC 键或点击右上角按钮退出全屏</p>
            </div>
          </div>
        </slot>
      </div>

      <!-- 全屏状态指示器 -->
      <div class="fullscreen-indicator" v-if="isFullscreen">
        <n-tag type="success" size="small">
          <template #icon>
            <n-icon>
              <Maximize />
            </n-icon>
          </template>
          全屏模式
        </n-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useMessage } from 'naive-ui'
import { Maximize, X } from '@vicons/tabler'

interface Props {
  title?: string
  autoEnter?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  autoEnter: false
})

const emit = defineEmits<{
  fullscreenChange: [isFullscreen: boolean]
  enterFullscreen: []
  exitFullscreen: []
}>()

const message = useMessage()
const fullscreenElement = ref<HTMLElement>()
const isFullscreen = ref(false)
const isLoading = ref(false)

// 检查浏览器是否支持全屏API
const isFullscreenSupported = () => {
  return !!(document.fullscreenEnabled ||
    (document as any).webkitFullscreenEnabled ||
    (document as any).mozFullScreenEnabled ||
    (document as any).msFullscreenEnabled)
}

// 获取当前全屏元素
const getFullscreenElement = () => {
  return document.fullscreenElement ||
    (document as any).webkitFullscreenElement ||
    (document as any).mozFullScreenElement ||
    (document as any).msFullscreenElement
}

// 进入全屏
const enterFullscreen = async () => {
  if (!isFullscreenSupported()) {
    message.warning('您的浏览器不支持全屏功能')
    return
  }

  if (!fullscreenElement.value) {
    message.error('全屏元素未找到')
    return
  }

  try {
    isLoading.value = true
    const element = fullscreenElement.value

    // 兼容不同浏览器的全屏API
    if (element.requestFullscreen) {
      await element.requestFullscreen()
    } else if ((element as any).webkitRequestFullscreen) {
      await (element as any).webkitRequestFullscreen()
    } else if ((element as any).mozRequestFullScreen) {
      await (element as any).mozRequestFullScreen()
    } else if ((element as any).msRequestFullscreen) {
      await (element as any).msRequestFullscreen()
    } else {
      throw new Error('不支持的全屏API')
    }

    emit('enterFullscreen')
  } catch (error) {
    console.error('进入全屏失败:', error)
    message.error('进入全屏失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 退出全屏
const exitFullscreen = async () => {
  try {
    // 兼容不同浏览器的退出全屏API
    if (document.exitFullscreen) {
      await document.exitFullscreen()
    } else if ((document as any).webkitExitFullscreen) {
      await (document as any).webkitExitFullscreen()
    } else if ((document as any).mozCancelFullScreen) {
      await (document as any).mozCancelFullScreen()
    } else if ((document as any).msExitFullscreen) {
      await (document as any).msExitFullscreen()
    }

    emit('exitFullscreen')
  } catch (error) {
    console.error('退出全屏失败:', error)
    message.error('退出全屏失败')
  }
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
  const fullscreenEl = getFullscreenElement()
  isFullscreen.value = !!fullscreenEl
  emit('fullscreenChange', isFullscreen.value)
}

// 监听键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  // ESC键退出全屏
  if (event.key === 'Escape' && isFullscreen.value) {
    exitFullscreen()
  }
  // F11键切换全屏（阻止默认行为，使用自定义全屏）
  if (event.key === 'F11') {
    event.preventDefault()
    if (isFullscreen.value) {
      exitFullscreen()
    } else {
      enterFullscreen()
    }
  }
}

// 组件挂载
onMounted(async () => {
  // 添加全屏状态变化监听
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('mozfullscreenchange', handleFullscreenChange)
  document.addEventListener('MSFullscreenChange', handleFullscreenChange)

  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)

  // 检查初始全屏状态
  handleFullscreenChange()

  // 自动进入全屏
  if (props.autoEnter) {
    await nextTick()
    enterFullscreen()
  }
})

// 组件卸载
onUnmounted(() => {
  // 移除事件监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange)
  document.removeEventListener('keydown', handleKeydown)

  // 如果组件卸载时还在全屏状态，退出全屏
  if (isFullscreen.value) {
    exitFullscreen()
  }
})

// 暴露方法给父组件
defineExpose({
  enterFullscreen,
  exitFullscreen,
  isFullscreen: readonly(isFullscreen),
  isSupported: isFullscreenSupported
})
</script>

<style scoped>
.fullscreen-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.fullscreen-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.fullscreen-btn {
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.fullscreen-content {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  overflow: hidden;
  position: relative;
}

/* 全屏状态样式 */
.fullscreen-container.is-fullscreen .fullscreen-content {
  border-radius: 0;
  background: #000;
}

.fullscreen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.fullscreen-title h2 {
  margin: 0;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.exit-btn {
  color: white !important;
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.exit-btn:hover {
  background: rgba(255, 255, 255, 0.2) !important;
}

.fullscreen-main {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.fullscreen-main.with-header {
  padding-top: 80px;
}

.fullscreen-indicator {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 100;
}

.default-content {
  text-align: center;
  color: white;
  max-width: 600px;
}

.content-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.content-center h3 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
}

.content-center p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .fullscreen-controls {
    top: 10px;
    right: 10px;
  }
  
  .fullscreen-header {
    padding: 12px 16px;
  }
  
  .fullscreen-title h2 {
    font-size: 16px;
  }
  
  .fullscreen-main {
    padding: 16px;
  }
  
  .fullscreen-main.with-header {
    padding-top: 70px;
  }
  
  .content-center h3 {
    font-size: 24px;
  }
  
  .content-center p {
    font-size: 14px;
  }
  
  .fullscreen-indicator {
    bottom: 10px;
    left: 10px;
  }
}

@media (max-width: 480px) {
  .fullscreen-main {
    padding: 12px;
  }
  
  .content-center h3 {
    font-size: 20px;
  }
  
  .content-center p {
    font-size: 13px;
  }
}

/* 全屏时的特殊样式 */
:fullscreen .fullscreen-content,
:-webkit-full-screen .fullscreen-content,
:-moz-full-screen .fullscreen-content,
:-ms-fullscreen .fullscreen-content {
  width: 100vw;
  height: 100vh;
  border-radius: 0;
}

/* 动画效果 */
.fullscreen-content {
  transition: all 0.3s ease;
}

.fullscreen-header {
  animation: slideDown 0.3s ease;
}

.fullscreen-indicator {
  animation: fadeIn 0.5s ease;
}

@keyframes slideDown {
  from {
    transform: translateY(-100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>